<script>
/**数据表展示模块 */
import FileRes from './FileRes';
import RelationRes from './RelationRes';
import TripartiteRes from './TripartiteRes';

//数据表分类常量
const DATA_SHEET_TYPES = {
  '92101': { name: '文件数据', component: 'FileRes', width: '400px' },
  '92200': { name: '关系数据源', component: 'RelationRes', width: '450px' },
  '92300': { name: '云盘数据', component: 'FileRes', width: '450px' },
  '92400': { name: '三方数据', component: 'TripartiteRes', width: '530px' },
};

//数据表子分类常量
const DATA_SHEET_SUBTYPES = {
  '92101': { name: 'Excel文件数据', color: '#dd6b66' },
  '92102': { name: 'CSV文件数据', color: '#91ca8c' },
  '92103': { name: 'JSON文件数据', color: '#b6a2de' },
  '92200': { name: '关系型数据', color: '#5ab1ef' },
  '92300': { name: '云盘数据', color: '#ffb980' },
  '92400': { name: '三方数据', color: '#2D8CF0' },
};

export default {
  name: 'DataSheet',
  components: {
    FileRes,
    RelationRes,
    TripartiteRes,
  },
  props: {
    pageSize: {
      //分页大小
      type: Number,
      default() {
        return 16;
      },
    },
    editEnabled: {
      //是否启用编辑模式
      type: Boolean,
      default() {
        return true;
      },
    },
    viewEnabled: {
      //是否启用预览模式
      type: Boolean,
      default() {
        return true;
      },
    },
  },
  data() {
    return {
      keyword: '', //查询关键字
      totalCount: 0, //总记录数
      pagedData: [], //列表分页数据
      selectModalOpened: false, //选择弹框是否打开
      dataModalOpened: false, //新增弹框是否打开
      dataTypes: Object.values(DATA_SHEET_TYPES), //可选的数据类型
      selectedType: null, //选择的新增数据类型
      modalWidth: '400px', //模态框宽度
    };
  },
  async beforeMount() {
    this.doQuery();
  },
  methods: {
    //获取分页数据
    async getPagedData(pageIndex) {
      const response = await api.datav.findAppList({
        objCondition: {
          name: this.keyword,
          typeId: Object.keys(DATA_SHEET_SUBTYPES).join(','),
        },
        orderby: 'createTime_desc',
        pageIndex: pageIndex,
        pageSize: this.pageSize,
      });
      this.pagedData = response.data.dataSource;
      this.pagedData.forEach(p => (p.data = JSON.parse(p.data)));
      return response;
    },
    //获取分页信息，并加载第一页
    async doQuery() {
      const response = await this.getPagedData(1);
      this.totalCount = response.data.pageInfo.totalCount;
    },
    //新增数据保存到数据库
    async saveData() {
      let dataModal = this.$refs.dataModal;
      //数据校验
      if (!dataModal.validateData()) return;
      //保存到数据库
      let addedModel = dataModal.getAddedModel();
      const userInfo = this.$store.state.user.info; //用户信息
      let appData = {
        appExEntity: {
          path: '',
          info: '',
          data: JSON.stringify(addedModel.data),
        },
        infoEntity: {
          userId: userInfo.id,
          orgId: userInfo.orgid,
          name: addedModel.name,
          alias: addedModel.name,
          typeId: addedModel.dataType,
        },
      };
      const response = await api.datav.addApp(appData);
      this.$Message.success('数据保存成功!');
      this.dataModalOpened = false;
      this.doQuery();
    },
    //删除数据
    deleteData(dataId) {
      this.$Modal.confirm({
        title: '删除提示',
        content: '数据删除后不可恢复，您确定要删除吗？',
        onOk: () => {
          api.datav.deleteApp({ id: dataId }).then(e => {
            this.doQuery();
            this.$Message.success('数据删除成功!');
          });
        },
      });
    },
    //预览数据
    viewData(item) {
      this.viewEnabled && this.$router.push(`./sheetViewer/${item.id}/${item.typeId}`);
      this.$emit('on-selectData', item);
    },
    //获取数据类型对应颜色
    getDataColor(typeId) {
      var typeInfo = DATA_SHEET_SUBTYPES[typeId] || {};
      return typeInfo.color || '#dd6b66';
    },
    //改变新增数据类型
    changeDataType(type) {
      this.selectedType = type.component;
      this.modalWidth = type.width;
    },
  },
};
</script>

<template>
  <div class="datasheet-host">
    <div class="datasheet-header">
      <Input
        v-model="keyword"
        placeholder="输入数据名称按Enter键搜索..."
        icon="search"
        @keyup.native.enter="doQuery()"></Input>
      <Button
        v-if="editEnabled"
        type="primary"
        @click="selectModalOpened=true">
        <Icon type="plus"></Icon>
        新增
      </Button>
      <Modal
        v-model="selectModalOpened"
        width="600px"
        @on-ok="dataModalOpened=true">
        <p slot="header">
          选择数据类型
        </p>
        <div class="new-data-btn">
          <Button
            v-for="type in dataTypes"
            :key="type.name"
            @click="changeDataType(type)">
            {{ type.name }}
          </Button>
        </div>
      </Modal>
      <Modal
        v-model="dataModalOpened"
        :width="modalWidth"
        @on-ok="saveData()">
        <component
          ref="dataModal"
          :key="new Date().getTime()"
          :is="selectedType">
        </component>
        <div slot="footer">
          <Button
            type="text"
            @click="dataModalOpened=false">取消</Button>
          <Button
            type="primary"
            @click="saveData">确定</Button>
        </div>
      </Modal>
    </div>
    <div class="datasheet-content">
      <Row
        type="flex"
        justify="start">
        <Card
          v-for="item in pagedData"
          :key="item.id"
          @click.native="viewData(item)">
          <a
            v-if="editEnabled"
            slot="extra"
            href="#"
            title="删除数据"
            @click.stop="deleteData(item.id)">
            <Icon type="close-circled"></Icon>
          </a>
          <div class="card-box clearfix">
            <i :style="{backgroundColor:getDataColor(item.typeId)}">{{ item.name|firstChar }}</i>
            <ul>
              <li>
                <label>数据名称：</label>
                {{ item.name }}
              </li>
              <li>
                <label>数据类型：</label>
                {{ item.typeName }}
              </li>
              <li>
                <label>创建时间：</label>
                {{ item.createTime|tickToDateString }}
              </li>
            </ul>
          </div>
        </Card>
      </Row>
      <Page
        :total="totalCount"
        :page-size="pageSize"
        @on-change="getPagedData"
      >
      </Page>
    </div>
  </div>
</template>

<style lang="less" scoped>
.datasheet-host {
  background-color: #ffffff;
  height: 100%;
  position: relative;
}

.datasheet-header {
  height: 50px;
  line-height: 50px;
  background-color: #f2f2f2;
  padding: 0 15px;
  .k-input-wrapper {
    width: 250px;
    margin-right: 5px;
  }
}

.datasheet-content {
  position: absolute;
  top: 50px;
  right: 0;
  bottom: 50px;
  left: 0;
  overflow-y: auto;
  .k-row-flex {
    margin: 20px 0 20px 15px;
  }
  .k-card {
    margin: 0 25px 15px 0;
    border-radius: 3px;
    border-color: #dfe3e5;
    .k-icon {
      font-size: 20px;
      color: #90a1ad;
      opacity: 0;
      transition: 0.3s opacity ease;
    }
    &:hover .k-icon {
      opacity: 1;
    }
  }
  .k-page {
    margin: 15px 40px 0 0;
    text-align: right;
  }
}

.new-data-btn {
  .k-btn {
    background: #ffffff;
    width: 23%;
    margin: 0 5px;
  }
}

.card-box {
  width: 330px;
  cursor: pointer;
  > i {
    float: left;
    width: 86px;
    height: 86px;
    line-height: 86px;
    text-align: center;
    font-style: normal;
    background-color: red;
    color: #ffffff;
    font-size: 40px;
    border-radius: 43px;
  }
  > ul {
    float: left;
    list-style: none;
    margin-left: 10px;
    > li {
      text-overflow: ellipsis;
      white-space: nowrap;
      overflow: hidden;
      max-width: 230px;
      height: 28px;
      line-height: 28px;
    }
    label {
      font-weight: bold;
      color: #333333;
    }
  }
}
</style>
